import {
  useState,
  useEffect,
  forwardRef,
  useImperativeHandle,
  useRef,
} from "react";
import axios from "axios";
import { Form, Input, Button, message } from "antd";

const Room = (props, ref) => {
  const btn = useRef();

  useImperativeHandle(ref, () => ({
    handClick() {
      btn.current.click();
    },
  }));

  const onFinish = (value) => {
    console.log(value);
    if (props.addInfo.m_id) {
      joinRoom(value);
      return;
    }
    getRoomInfo(value);
  };

  const getRoomInfo = async (projectInfo) => {
    const res = await axios.post("http://127.0.0.1:4399/device/addRoom", {
      data: {
        ...projectInfo,
        m_id: props.m_id,
      },
    });
    console.log(res);
    if (!res.data) return;
    if (res.data.code == 200) {
      message.info("创建帮会成功~,亲爱的帮主!!!");
      props.setIsModalVisible(false);
      props.getRoomInfo();
    } else {
      message.info(res.data.code);
    }
    //TODO: 清空输入框
  };

  const joinRoom = async (value) => {
    const res = await axios.post("http://127.0.0.1:4399/device/joinRoom", {
      data: {
        m_id: props.m_id,
        sync_id: props.addInfo.sync_id,
        ...value,
      },
    });
    console.log(res);
    if (!res.data.code) return;
    if (res.data.code == 200) {
      message.info(res.data.message);
      // 刷新列表
      props.getRoomInfo();
    } else if (res.data.code == 400) {
      message.info(res.data.message);
    } else {
      message.info(res.data.code);
    }
    props.setAddInfo({});
    props.setIsModalVisible(false);
  };

  return (
    <>
      <Form
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label={props.addInfo.m_id ? "要加入项目名称" : "帮会名称(项目名称)"}
          name="project_name"
          rules={[{ required: true, message: "请输入项目名称" }]}
          initialValue=""
        >
          <Input />
        </Form.Item>

        <Form.Item
          label={props.addInfo.m_id ? "要加入项目地址" : "帮会地址(项目地址)"}
          name="project_path"
          rules={[{ required: true, message: "请输入项目地址" }]}
          initialValue=""
        >
          <Input />
        </Form.Item>
        {!props.addInfo.m_id ? (
          <Form.Item label="帮会描述" name="remarks">
            <Input />
          </Form.Item>
        ) : (
          ""
        )}
        <Form.Item style={{ display: "none" }}>
          <Button type="primary" htmlType="submit" ref={btn}></Button>
        </Form.Item>
      </Form>
    </>
  );
};

export default forwardRef(Room);
